'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const utility = require('../../common/utility');
const constant = require('../../common/constant');
const logger = require('../../common/logutility').logger('login');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        res.render('./com/login');
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        let couTel = req.body.userTel;
        let couPwd = utility.encrypt(req.body.userPwd);
        let cou = yield dbutility.couModel.getUserAuth(couTel, couPwd);

        if (cou) {
            //将登陆用户信息放入session中
            req.session.userTel = req.body.userTel;

            if (req.body.cmdType === 'L') {
                //快递员登陆
                req.session.loginType = constant.LOGIN_TYPE_COU;
                res.redirect('/couIndex');
            } else if (req.body.cmdType === 'R' && cou.couCmp === constant.ADM_CMP) {
                //管理者登陆
                req.session.loginType = constant.LOGIN_TYPE_ADM;
                res.redirect('/admIndex');
            } else {
                return res.render('login', { userTel: req.body.userTel, errorInfo: '账号或者密码输入错误！' });
            }
            logger.info('User Login:' + req.session.userTel);
            logger.info('Login Type:' + req.session.loginType);
        } else {
            return res.render('./com/login', { userTel: req.body.userTel, errorInfo: '账号或者密码输入错误！' });
        }
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;